package com.example.fastshare;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.graphics.Bitmap;
import android.os.Environment;
import android.text.format.Time;

public class Item {
	private String avatarID;
	private String lastMsg;
	private String imageID;
	private Time time;
	public boolean isReceived;
	private String strTime;
	private String userId;

	public Item(String id, String msg, Time lastTimes, boolean received) {
		this.avatarID = id;
		this.lastMsg = msg;
		this.imageID = null;
		this.time = lastTimes;
		this.isReceived = received;
	}

	public void setAvatar(String id) {
		this.avatarID = id;
	}

	public String getAvatarID() {
		return this.avatarID;
	}

	public void setLastmsg(String content) {
		this.lastMsg = content;
	}

	public String getLastMsg() {
		return this.lastMsg;
	}

	public void setImage(String id) {
		this.imageID = id;
	}

	public String getImageID() {
		return this.imageID;
	}

	public void setTime(Time lastTime) {
		this.time = lastTime;
	}

	public Time getTime() {
		if (this.time != null) {
			this.time.setToNow();
			return this.time;
		}
		return null;
	}

	public void setIsReceived(boolean received) {
		this.isReceived = received;
	}

	public void SaveImage(Bitmap image, String name) {

		File imageFile = null;
		File dir = new File("/sdcard/Fastshare/");
		if (dir.exists() == false) {
			dir.mkdirs(); // create folders where write files
		}
		int imageNum;
		if (dir.list() == null)
			imageNum = 1;
		else
			imageNum = dir.list().length + 1;
		try {
			String fileName = "Image" + name + String.valueOf(imageNum);
			fileName = fileName.replaceAll("(\\p{Punct})", "");
			fileName += ".png";
			imageFile = new File(dir, fileName);

			if (!imageFile.exists()) {
				imageFile.createNewFile();
			}
			FileOutputStream out = new FileOutputStream(imageFile);
			image.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			out.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
		if (imageFile != null) {
			this.imageID = imageFile.getAbsolutePath();
		} else {
			this.imageID = null;
		}
	}

	/**
	 * @return the strTime
	 */
	public synchronized String getStrTime() {
		return strTime;
	}

	/**
	 * @param strTime
	 *            the strTime to set
	 */
	public synchronized void setStrTime(String strTime) {
		this.strTime = strTime;
	}

	/**
	 * @return the userId
	 */
	public synchronized String getUserId() {
		return userId;
	}

	/**
	 * @param userId the userId to set
	 */
	public synchronized void setUserId(String userId) {
		this.userId = userId;
	}

}
